<template>
  <div class="box">
    <h3>欢迎来到德莱联盟</h3>
    <el-form :model="user" :rules="rules" ref="loginform">
      <el-form-item prop="username">
        <el-input v-model="user.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="user.password" placeholder="请输入密码" type='password'></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="addlogin">立即登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      user: {
        username: "",
        password: "",
      },
      //表单校验
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    addlogin() {
      this.$http
        .post("/admin/login", this.user)
        .then((res) => {
          //成功
          this.$refs.loginform.validate((valid) => {
            if (valid) {
              console.log(res)
              if (res.data.msg == "ok") {
                //跳转页面
                this.$router.push('/home')
                //提示信息
                this.$message({
                  message: "登录成功",
                  type: "success",
                });
                //存储token
                var obj={'username':this.user.username,'token':res.data.data.token}
                this.$store.commit('login',obj)
              }
            }else{
                return false
            }
          });
        })
        //失败
        .catch((err) => {
          if(err.response.data.msg=='密码错误'){
               this.$message({
                  message: "密码错误",
                  type: "warning",
                });
          }
        });
    },
  },
  mounted() {},
};
</script>

<style lang='scss' scoped>
.box {
  width: 40%;
  border: 1px solid #dddddd;
  padding: 10px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -60%);
  h3 {
    width: 100%;
    text-align: center;
    height: 40px;
    line-height: 40px;
    border-bottom: 1px #dddddd;
  }
}
button {
  width: 100%;
}
</style>